package com.atXiao.video.pubsub;

import com.atXiao.video.common.rspEnum.RedisKeyEnum;
import com.atXiao.video.entity.User;
import com.atXiao.video.entity.req.common.MessageDto;
import com.atXiao.video.service.UserService;
import com.atXiao.video.service.impl.SubscribeServiceImpl;
import com.atXiao.video.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * redis默认的消息监听接口(MessageListener)
 * 用于处理用户的订阅退订相关信息，将接口进行解耦
 * 此处其实是为了解耦而解耦，主要是想熟练一下redis的发布订阅迷失。此处完全可以使用list结构，订阅的时候往list中塞值，获取通知接口从list中再获取，也是可以的
 *
 */
@Slf4j
@Component
public class UserSubscribeListener implements MessageListener {

    private final static Logger logger = LoggerFactory.getLogger(UserSubscribeListener.class);


    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    UserService userService;

    @Override
    public void onMessage(Message message, byte[] pattern) {

        // 接收的topic
        log.info("订阅的Topic:" + new String(pattern));

        //序列化对象（特别注意：发布的时候需要设置序列化；订阅方也需要设置序列化）
        MessageDto messageDto = (MessageDto) redisTemplate.getValueSerializer().deserialize(message.getBody());
        String[] split = messageDto.getContent().split(",");
        //当前用户编号
        String youtubeId=split[0];
        //要订阅的用户编号
        String subscribeId=split[1];
        User youtube = userService.getById(youtubeId);
        User subScribe = userService.getById(subscribeId);
        if (ObjectUtils.isEmpty(youtube)||ObjectUtils.isEmpty(subScribe)){
            logger.error("用户为空");
        }
        String yourName = youtube.getUsername();
        String scribeUsername = subScribe.getUsername();
        String msg=yourName+"关注了你";
        redisUtils.rSet(RedisKeyEnum.user_sub_prefix.getKeyPrefix()+subscribeId,msg);
        logger.info("订阅模型处理消息成功，流水号为:{}",messageDto.getTrace());
    }
}

